//
//  LTFirstViewController.m
//  LearnTeacher
//
//  Created by yang bo on 2024/4/13.
//

#import "LTFirstViewController.h"

#import "LTListenSaidController.h"

#import "LTBookSyncCell.h"
#import "LTCollectCell.h"
#import "LTBookExpandCell.h"
#import "LTFirstBannerModel.h"
#import "LTFirstCollectModel.h"
#import <Masonry/Masonry.h>
#import "LTFirstAPIManager.h"
#import "LTFirstHeaderView.h"
#import "LTWebViewController.h"
#import "LTChooseContentViewController.h"
#import "LTChooseUnitViewController.h"
#import "LTHomeworkAipManager.h"
#import "LTChooseUnitModel.h"
#import "LTUpgradeTools.h"
#import "LTUpgradeTools.h"

@interface LTFirstViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *bannerList;
@property (nonatomic, strong) NSArray *collectList;
@property(strong, nonatomic) NSString *content;
@property (nonatomic, strong) UILabel *descLabel;
@property (nonatomic, strong) LTFirstHeaderView *headerView;
@property(strong, nonatomic) NSString *versionId;
@property(strong, nonatomic) NSString *versionName;
@property(strong, nonatomic) NSString *unitId;
@end

@implementation LTFirstViewController

- (LTFirstHeaderView *)headerView {
    if(!_headerView) {
        _headerView = [LTFirstHeaderView headerView];
        _headerView.frame = CGRectMake(0, 0, SCREEN_W, (SCREEN_W - 32) * 150 / 342 + 16);
    }
    return _headerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    [self setup];
    [self getFirstData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(unitChanged:) name:ChooseUnitSuccess object:nil];
}

- (void)unitChanged:(NSNotification *)notif {
//    self.content = [NSString stringWithFormat:@"%@", notif.object];
//    [self.tableView reloadSection:0 withRowAnimation:UITableViewRowAnimationNone];
//    self.descLabel.text = notif.userInfo[@"content"];
//    self.versionName = self.descLabel.text;
//    self.versionId = notif.userInfo[@"id"];
    [self getFirstData];
}

- (void)tapGesture {
    LTChooseContentViewController *contentVC = [[LTChooseContentViewController alloc] init];
    UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:contentVC];
    navc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self.navigationController presentViewController:navc animated:NO completion:^{}];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self renderNavBarWithBackgroundImage:[UIImage imageWithColor:LTClearColor] backgroundColor:[UIColor redColor] shadowColor:nil textAttributeDic:@{NSForegroundColorAttributeName:rgba(255, 255, 255, 1),NSFontAttributeName:MFontWithSize(17)} enableScrollEdgeAppearance:NO];
    [[LTUpgradeTools shared] checkTeacherversion];
}

- (void)getFirstData {
    NSLog(@"token = %@", LTApp.token);
    [LTFirstAPIManager getFirstDataResult:^(NSDictionary * _Nonnull dic) {
        if ([dic[@"code"] integerValue] == 1) {
             self.bannerList = [NSArray modelArrayWithClass:[LTFirstBannerModel class] json:dic[@"data"][@"banner"]];
            self.collectList = [NSArray modelArrayWithClass:[LTFirstCollectModel class] json:dic[@"data"][@"collect"]];
            self.tableView.tableHeaderView = self.headerView;
            self.headerView.frame = CGRectMake(0, 0, SCREEN_W, (SCREEN_W - 32) * 150 / 342 + 26);
            self.headerView.bannerList = self.bannerList;
            NSDictionary *textbooksp = dic[@"data"][@"unit"];
            if ([textbooksp isKindOfClass:[NSDictionary class]]) {
                NSString *book_name = textbooksp[@"book_name"]; //内容
                if ([book_name isKindOfClass:[NSNull class]] || book_name.length == 0) {
                    self.versionName = @"请选择内容";
                }else {
                    self.versionName = book_name;
                    self.versionId = textbooksp[@"versionId"];
                }
                self.descLabel.text = self.versionName;
                NSString *unit_name = textbooksp[@"name"];
                if ([unit_name isKindOfClass:[NSNull class]] || unit_name.length == 0) {
                    self.content = @"请选择单元";
                }else {
                    self.content = unit_name;
                    self.unitId = [NSString stringWithFormat:@"%ld", [textbooksp[@"unitid"] integerValue]];
                }
            }else {
                self.versionName = @"请选择内容";
                self.descLabel.text = self.versionName;
                self.content = @"请选择单元";
            }
            [self.tableView reloadData];
        }
    }];
}

- (void)getUnitData:(NSString *)identifier name:(NSString *)name {
    __weak typeof(self) weakSelf = self;
    [SVProgressHUD show];
    [LTHomeworkAipManager getTextBookUnitWithParam:@{@"id":identifier} result:^(NSDictionary * _Nonnull dic) {
        id data = dic[@"data"];
        if ([data isKindOfClass:[NSArray class]]) {
            NSArray *dataArray = (NSArray *)data;
            NSMutableArray *models = @[].mutableCopy;
            for (NSDictionary *dict in dataArray) {
                LTChooseUnitModel *model = [LTChooseUnitModel modelWithJSON:dict];
                [models addObject:model];
            }
            if (models.count == 0) {
                [SVProgressHUD showImage:nil status:@"暂无数据~"];
            }else {
                [SVProgressHUD dismiss];
                LTChooseUnitViewController *contentVC = [[LTChooseUnitViewController alloc] init];
                contentVC.dataSource = models;
                contentVC.name = name;
                contentVC.versionId = identifier;
                contentVC.showColor = YES;
                UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:contentVC];
                navc.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [weakSelf.navigationController presentViewController:navc animated:NO completion:^{
                    
                }];
            }
        }
    }];
}

- (void)setup {
    UIImageView *bgImgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_W * 50 / 75)];
    bgImgV.image = [UIImage imageNamed:@"ic_top_background"];
    [self.view addSubview:bgImgV];
    UIView *searchBarView = [[UIView alloc] initWithFrame:CGRectMake(0, LTStatusBarHeight + 56, SCREEN_W, 44)];
    UITextField *textFiled = [[UITextField alloc] initWithFrame:CGRectMake(16, 0, SCREEN_W - 32, 48)];
    textFiled.layer.cornerRadius = 12;
    textFiled.layer.shadowColor = [UIColor colorWithRed:196/255.0 green:203/255.0 blue:214/255.0 alpha:0.1000].CGColor;
    textFiled.layer.shadowOffset = CGSizeMake(0,6);
    textFiled.layer.shadowOpacity = 1;
    textFiled.layer.shadowRadius = 58;
    textFiled.backgroundColor = [UIColor whiteColor];
    UIView *searchBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 48)];
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchBtn setImage:[UIImage imageNamed:@"ic_first_search"] forState:UIControlStateNormal];
    searchBtn.frame = CGRectMake(0, 12, 24, 24);
    [searchBgView addSubview:searchBtn];
    textFiled.rightView = searchBgView;
    textFiled.rightViewMode = UITextFieldViewModeAlways;
    [searchBarView addSubview:textFiled];
    [self.view addSubview:searchBarView];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LTStatusBarHeight + 115, SCREEN_W, SCREEN_H) style:UITableViewStyleGrouped];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.sectionFooterHeight = 0;
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
    self.tableView = tableView;
    tableView.backgroundColor = [UIColor clearColor];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LTCollectCell class]) bundle:nil] forCellReuseIdentifier:@"CollectID"];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LTBookSyncCell class]) bundle:nil] forCellReuseIdentifier:@"SYNCID"];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LTBookExpandCell class]) bundle:nil] forCellReuseIdentifier:@"EXPANDID"];
    tableView.dataSource = self;
    tableView.delegate = self;
    [self.view addSubview:tableView];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(LTStatusBarHeight + 105);
        make.bottom.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0) {
        return (SCREEN_W - 32) * 216 / 700 + 5;
    }else if (indexPath.section == 1) {
        return 44 * 2 + 40 + 24 ;
    }else {
        return (SCREEN_W - 66) / 3 * 150 / 106 + 52 + 18 + 22;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if(indexPath.section == 0) {
        LTBookSyncCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SYNCID"];
        cell.contentLabel.text = self.content;
        [cell setChangeUnitHandler:^{
            if ([weakSelf.versionId integerValue] > 0) {
                [weakSelf getUnitData:weakSelf.versionId name:weakSelf.versionName];
            }else {
                LTChooseContentViewController *contentVC = [[LTChooseContentViewController alloc] init];
                UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:contentVC];
                navc.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [weakSelf.navigationController presentViewController:navc animated:NO completion:^{}];
            }
        }];
        return cell;
    }else if (indexPath.section == 1) {
        LTBookExpandCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EXPANDID"];
        cell.itemTapBlock = ^(NSInteger type, NSString *name) {
            NSLog(@"点击了 - %ld, name = %@", type, name);
            LTWebViewController *vc = [LTWebViewController new];
            [vc loadUrl:[NSString stringWithFormat:@"https://d-xueer.bigchun.com/techtest/#/pages/listen/index?token=%@&title=%@&type=%ld", LTApp.token, name, type]];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }else {
        LTCollectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CollectID"];
        cell.list = self.collectList;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 42;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if ([self.versionId integerValue] > 0 && self.unitId.length > 0) {
            LTWebViewController *vc = [LTWebViewController new];
            [vc loadUrl:[NSString stringWithFormat:@"https://d-xueer.bigchun.com/techtest/#/pages/secCatalogue/jiaocaitongbu?id=%@&typd=%@&title=教材同步&token=%@", self.unitId, self.versionId, LTApp.token]];
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            LTChooseContentViewController *contentVC = [[LTChooseContentViewController alloc] init];
            UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:contentVC];
            navc.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self.navigationController presentViewController:navc animated:NO completion:^{}];
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *secHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 42)];
//    secHeaderView.backgroundColor = [UIColor redColor];
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(20,14,4,14);
    // gradient
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0,0,4,14);
    gl.startPoint = CGPointMake(0.67, 0.04);
    gl.endPoint = CGPointMake(0.31, 0.87);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:28/255.0 green:169/255.0 blue:254/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:0/255.0 green:121/255.0 blue:255/255.0 alpha:1.0].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    view.layer.cornerRadius = 2;
    [view.layer addSublayer:gl];
    [secHeaderView addSubview:view];
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(32, 0, 70, 42)];
    titleLab.font = [UIFont boldSystemFontOfSize:16];
    titleLab.text = section == 0 ? @"教材同步" : section == 1 ? @"课外拓展" : @"收藏列表";
    [secHeaderView addSubview:titleLab];
    UIImageView *rightArrowImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_right_arrow"]];
    [secHeaderView addSubview:rightArrowImgV];
    [rightArrowImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(0);
        make.width.mas_equalTo(5);
        make.height.mas_equalTo(9);
    }];
    rightArrowImgV.hidden = section != 0;
    UILabel *descLab = [[UILabel alloc] init];
    descLab.textColor = rgbHex(0x999999, 1);
    descLab.font = [UIFont systemFontOfSize:12];
    descLab.hidden = section != 0;
    [secHeaderView addSubview:descLab];
    [descLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(rightArrowImgV.mas_left).offset(-5);
        make.centerY.mas_equalTo(0);
    }];
    _descLabel = descLab;
    _descLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture)];
    [_descLabel addGestureRecognizer:tap];
    if ([self.versionName isKindOfClass:[NSNull class]] || self.versionName.length == 0) {
        _descLabel.text = @"请选择内容";
    }else {
        _descLabel.text = self.versionName;
    }
    return secHeaderView;
}

  
@end
